package common.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.lang.StringUtils;

import common.impl.exception.ServiceException;
import common.interf.IFileHandle;

public class FileHandleImpl implements IFileHandle {
	public String saveUploadFile(File file, String path, String fn) {
		int index = fn.lastIndexOf('.');
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();// 创建个文件夹
		String newFileName = null;
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		if (index != -1)
			newFileName = uuid + fn.substring(index);// 生成新文件名
		else
			newFileName = uuid;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			File newFile = new File(dir, newFileName);
			FileOutputStream fos = new FileOutputStream(newFile);
			bos = new BufferedOutputStream(fos);

			byte[] buf = new byte[4096];
			int len = -1;
			while ((len = bis.read(buf)) != -1) {
				bos.write(buf, 0, len);
			}
			
		} catch (Exception e) {

		} finally {
			try {
				if (null != bis)
					bis.close();
			} catch (IOException e) {
			}

			try {
				if (null != bos)
					bos.close();
			} catch (IOException e) {
			}
		}
		return newFileName;
	}

	/**
	 * 保存图片文件
	 * 
	 * @param file
	 *            ：文件名
	 * @param path
	 *            ：保存路径
	 * @param addStr
	 *            ：附加串
	 * @return 新文件名
	 */
	public String savePicFile(File file, String path, String addStr) {
		String fn = file.getName();
		File dir = new File(path);

		if (!dir.exists())
			dir.mkdirs();// 创建文件夹

		String newFileName = MD5Transform.EncoderByMd5(fn, "utf-8");
		int index = fn.lastIndexOf('.');

		Long ti = Calendar.getInstance().getTimeInMillis();
		if (index != -1)
			newFileName += fn.substring(0, index) + ti + "_" + addStr
					+ fn.substring(index);// 生成新文件名
		else
			newFileName += ti + "_" + addStr;

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			File newFile = new File(dir, newFileName);
			FileOutputStream fos = new FileOutputStream(newFile);
			bos = new BufferedOutputStream(fos);

			byte[] buf = new byte[4096];
			int len = -1;
			while ((len = bis.read(buf)) != -1) {
				bos.write(buf, 0, len);
			}
			
		} catch (Exception e) {

		} finally {
			try {
				if (null != bis)
					bis.close();
			} catch (IOException e) {
			}

			try {
				if (null != bos)
					bos.close();
			} catch (IOException e) {
			}
		}
		return newFileName;
	}

	/**
	 * 保存文件
	 * 
	 * @param file
	 *            :要保存的file
	 * @param savePath
	 *            :保存路径
	 * @param fn
	 *            :新文件名，为空则去file文件名
	 * @return 新文件名
	 */
	public String saveFile(File file, String savePath, String fn) {
		if (null == file)
			return null;
		File dir = new File(savePath);
		if (!dir.exists())
			dir.mkdirs();// 创建个文件夹
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		
		try {
			FileInputStream fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			if (null == fn)
				fn = file.getName();
			File newFile = new File(dir, fn);
			FileOutputStream fos = new FileOutputStream(newFile);
			bos = new BufferedOutputStream(fos);

			byte[] buf = new byte[4096];
			int len = -1;
			while ((len = bis.read(buf)) != -1) {
				bos.write(buf, 0, len);
			}
			
		} catch (Exception e) {

		} finally {
			try {
				if (null != bis)
					bis.close();
			} catch (IOException e) {
			}

			try {
				if (null != bos)
					bos.close();
			} catch (IOException e) {
			}
		}
		return fn;
	}

	/**
	 * 解压文件
	 */
	public Boolean unZipFile(File zipFile,String path) throws Exception{
		//创建保存的路径
		File pathFile = new File(path);
		//路径存在就删除
		if(pathFile.exists())
			removeDir(pathFile);
		pathFile.mkdirs();
		
		ZipFile zip = new ZipFile(zipFile);
		//读取zip文件
		Enumeration entries = zip.entries();
		for(;entries.hasMoreElements();){
			ZipEntry zipEntry = (ZipEntry)entries.nextElement();
			String zipEntryName = zipEntry.getName();
			
			String outPutPath = (path+"/"+zipEntryName).replaceAll("\\\\", "/");
			//判断路径是否存在，不存在则创建文件路径
			File file = new File(outPutPath.substring(0,outPutPath.lastIndexOf("/")));
			if(!file.exists()){
				file.mkdirs();
			}
			if(new File(outPutPath).isDirectory()){
				continue;
			}
			InputStream in = null;
			OutputStream out = null;
			//创建输入流
			try{
				in = zip.getInputStream(zipEntry);
				out = new FileOutputStream(outPutPath);
				byte[] buf = new byte[1024];
				int len;
				while((len = in.read(buf))>0){
					out.write(buf,0,len);
				}
			}catch(Exception e){
				
			}finally{
				try{
					in.close();
					out.close();
					
				}catch(Exception e){
					
				}
			}
		}
		zip.close();
		return true;
	}
	
	public void removeUriDir(String dirPath, String contextPath, String realPath) {
		int ind = dirPath.indexOf(contextPath);
		if (ind != -1) {
			dirPath = dirPath.substring(ind + contextPath.length() + 1);
		}
		File file = new File(realPath + dirPath);
		if (file.exists())
			removeDir(file);
	}

	/**
	 * 删除文件夹
	 * 
	 * @param dir
	 *            :要删除的目录
	 */
	public void removeDir(File dir) {
		if (null == dir)
			return;
		if (dir.exists()) {
			if (dir.isDirectory()) {
				if (dir.listFiles().length > 0) {
					File delFile[] = dir.listFiles();
					for (int i = 0, len = dir.listFiles().length; i < len; i++) {
						removeDir(delFile[i]);
					}
				}
			}
			dir.delete();
		}
	}

	/**
	 * 删除网络文件
	 */
	public boolean removeUriFile(String filePath, String contextPath,
			String realPath) {
		if(StringUtils.isEmpty(filePath))
			return false;
		int ind = filePath.indexOf(contextPath);
		if (ind != -1) {
			filePath = filePath.substring(ind + contextPath.length() + 1);
		}
		File file = new File(realPath + filePath);
		if (file.exists())
			file.delete();
		return true;
	}

	// 获取文件类型
	public String getFileType(File file) throws Exception {
		URL u = new URL("file:///" + file.getAbsolutePath());
		URLConnection uc = u.openConnection();
		String type = uc.getContentType();

		return type;
	}

	public void moveFile(File fromUrl, File toUrl) {
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new FileInputStream(fromUrl);
			os = new FileOutputStream(toUrl);
			byte[] buff = new byte[1024];
			int len;
			while ((len = is.read(buff, 0, 1024)) != -1) {
				os.write(buff, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != is)
					is.close();
				if (null != os)
					os.close();
			} catch (Exception e2) {
			}
		}
	}

	public void saveFile(File file, String pathName) {
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new FileInputStream(file);
			os = new FileOutputStream(new File(pathName));
			byte[] buff = new byte[10240];
			int len = -1;
			while ((len = is.read(buff, 0, 10240)) > -1) {
				os.write(buff, 0, len);
			}
		} catch (Exception e) {
		} finally {
			try {
				if (null != is)
					is.close();
				if (null != os)
					os.close();
			} catch (Exception e) {
			}
		}
	}
	
	//赋值文件或文件夹到指定的目录
	public void copyFile(){
		
	}
}
